<template>
  <div>
    <div class="search_box">
      <el-form
        :inline="true"
        ref="formRef"
        :model="formData"
        class="demo-form-inline"
      >
        <!-- <el-form-item>
          <el-input
            v-model="formData.keyword"
            placeholder="请输入剧集ID或标题"
            clearable
            @clear="getList"
          />
        </el-form-item> -->
        <el-form-item>
          <el-button
            type="primary"
            @click="getList(1)"
            v-auth="'api:agent:userManage:search'"
          >
            <el-icon style="margin-right: 5px">
              <Search />
            </el-icon>
            刷 新
          </el-button>
          <span
            style="margin: 0 12px; color: #666"
            v-auth-all="[
              'api:agent:userManage:add',
              'api:agent:userManage:search',
            ]"
            >|</span
          >
          <el-button
            type="primary"
            @click="addUser"
            v-auth="'api:agent:userManage:add'"
          >
            <el-icon style="margin-right: 5px">
              <Plus />
            </el-icon>
            新 增
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table_box_wrapper">
      <custom-table
        :loading="loading"
        :columns="columns"
        :tableData="tableData"
        :pageObj="pageObj"
        @sizechange="sizechange"
        @currentChange="currentChange"
        class="table_box"
      >
        <template #dataScope="{ scope }">
          {{
            scope.row.dataScope == "All"
              ? "全部"
              : scope.row.dataScope == "Self"
              ? "仅自己"
              : "同步其他用户数据"
          }}
        </template>
        <template #enabled="{ scope }">
          <el-switch
            style="

--el-switch-on-color: #13ce66"
            :modelValue="scope.row.enabled"
            inline-prompt
            active-text="启用"
            inactive-text="禁用"
            @click.stop="handdelEnable(scope.row)"
          />
        </template>
        <template #operator="{ scope }">
          <span
            class="operationClick isBlock"
            @click.stop="handleEdit(scope.row)"
            v-auth="'api:agent:userManage:update'"
          >
            编辑
          </span>
          <span
            class="operationClick isBlock"
            @click.stop="handlePower(scope.row)"
            v-auth="'api:agent:userManage:setPower'"
          >
            数据权限
          </span>
          <el-popconfirm
            title="请确认是否需要重置密码?"
            @confirm.stop="handleReset(scope.row)"
          >
            <template #reference>
              <span
                v-auth="'api:agent:userManage:resetPassword'"
                class="operationClick isBlock"
              >
                重置密码
              </span>
            </template>
          </el-popconfirm>
        </template>
      </custom-table>
    </div>

    <!-- 新增编辑 -->
    <userInfo ref="userRef" @success="getList(1)" />
    <dataPower ref="powerRef" @success="getList(1)" />
  </div>
</template>

<script lang="ts" setup>
import customTable from "@/components/CustomTable/index.vue";
import userInfo from "./components/userInfoDialog.vue";
import dataPower from "./components/dataPower.vue";
import { Plus, Search } from "@element-plus/icons-vue";
import type { Action } from "element-plus";
import { getUserList, setEnable, resetPassword } from "@/api/userManage/index";
import { randomString, copyLink } from "@/utils/tools";
import { useUserStore } from "@/store/modules/user";

const userName = useUserStore().user?.userName;
const loading = ref<boolean>(false);
const formData = reactive({
  currentPage: 1,
  pageSize: 10,
  // keyword: "",
});
const tableData = ref<Array<any>>([]);

interface modelPage {
  pageNo: number;
  pageSize: number;
  total: number;
}
const pageObj = reactive<modelPage>({
  pageNo: 1,
  pageSize: 10,
  total: 0,
});

const columns = reactive([
  { label: "用户ID", prop: "id", minWidth: 145 },
  { label: "昵称", prop: "name", minWidth: 120 },
  { label: "账号", prop: "userName", minWidth: 120 },
  {
    label: "数据权限",
    prop: "dataScope",
    slotName: "dataScope",
    minWidth: 120,
  },
  { label: "角色", prop: "roleNames", minWidth: 120 },
  { label: "状态", prop: "enabled", slotName: "enabled", minWidth: 120 },
  { label: "操作", prop: "operator", slotName: "operator", width: 120 },
]);

// 启用 禁用
const handdelEnable = (val: Record<string, any>) => {
  ElMessageBox.alert(
    `确定要${val?.status == 1 ? "禁用" : "启用"} "${val?.userName}" 账号吗？`,
    "提醒",
    {
      confirmButtonText: "确定",
      callback: (action: Action) => {
        if (action === "confirm") {
          setEnable({ enabled: !val.enabled, userId: val.id }).then(() => {
            ElMessage.success(`${val?.status ? "禁用" : "启用"}成功`);
            getList(1);
          });
        }
      },
    }
  );
};

// 新增
const userRef = ref();
const addUser = () => {
  userRef.value.showDialog();
};
// 编辑
const handleEdit = (val: Record<string, any>) => {
  userRef.value.showDialog(val);
};

// 数据权限
const powerRef = ref();
const handlePower = (val: Record<string, any>) => {
  powerRef.value.showDialog(val);
};

// 重置密码
const handleReset = (val: Record<string, any>) => {
  let password = randomString(8);
  resetPassword({ id: val.id, password: password }).then(() => {
    let test = `昵称：“${val.name}” 的账号登录密码已重置为：${password} 
  ，请保存密码发送给他。`;
    ElMessageBox.alert(test, "重置密码成功", {
      confirmButtonText: "确认&复制",
      callback: () => {
        copyLink(password);
        getList(1);
      },
    });
  });
};

const getList = (val = 0) => {
  // if (!val) {
  //   formData.currentPage = pageObj.pageNo;
  //   formData.pageSize = pageObj.pageSize;
  // } else {
  //   formData.currentPage = pageObj.pageNo = val === 1 ? val : 1;
  //   formData.pageSize = pageObj.pageSize = val === 1 ? 10 : pageObj.pageSize;
  // }
  formData.currentPage = pageObj.pageNo;
  formData.pageSize = pageObj.pageSize;

  loading.value = true;
  getUserList(formData)
    .then((res: Record<string, any>) => {
      tableData.value = res.data?.list;
      pageObj.total = Number(res.data?.total);
      loading.value = true;
    })
    .finally(() => {
      loading.value = false;
    });
};

const currentChange = (val: number) => {
  pageObj.pageNo = val;
  getList();
};

const sizechange = (val: number) => {
  pageObj.pageSize = val;
  getList(2);
};

onMounted(() => {
  getList();
});
</script>
<style scoped lang="scss"></style>
